#导入数据集

import numpy as np
from sklearn.model_selection import train_test_split

data_file = ""
raw_df = np.loadtxt(data_file, delimiter=',', encoding='utf-8')
x = raw_df[:, :2]
y = raw_df[:, 2]
print(f'特征形状：{x.shape}')  #应该是(100, 2)
print(f'标签形状：{y.shape}')  #应该是(100,)

print(f'x_1: 最小值{x[:, 0].min():.2f}, 最大值{x[:, 0].max():.2f}, 均值{x[:, 0].mean():.2f}, 个数{x[:, 0].shape[0]}')
print(f'x_2: 最小值{x[:, 1].min():.2f}, 最大值{x[:, 1].max():.2f}, 均值{x[:, 1].mean():.2f}, 个数{x[:, 1].shape[0]}')

x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3, random_state=1)

from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score

#建立逻辑回归模型
model = LogisticRegression()  
model.fit(x_train, y_train)
ac = accuracy_score(y_test, model.predict(x_test))
print(f'模型预测准确率(Accuracy)：{ac:.4}')

#规划网格
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
import numpy as np
#绘制分类界面

N, M = 500, 500  #定义网格密度，行列（网格采样点的个数，采样点越多，分类界面图越精细）
t1 = np.linspace(0, 100, N)  #生成采样点的横坐标值
t2 = np.linspace(0, 100, M)  #生成采样点的纵坐标值

x1, x2 = np.meshgrid(t1, t2)  #生成网格采样点
x_new = np.stack((x1.flat, x2.flat), axis=1)  #将采样点作为测试点
y_predict = model.predict(x_new)  #预测测试点的值
y_hat = y_predict.reshape(x1.shape)  #与x1设置相同的形状

#可视化
iris_cmap = ListedColormap(['#ACC6C0', '#FF8080', '#A0A0FF'])  #设置分类界面的颜色
plt.pcolormesh(x1, x2, y_hat, cmap=iris_cmap)  #绘制分类界面
#绘制两种录取结果
plt.scatter(x[y == 0, 0], x[y == 0, 1], s=30, c='g', marker='^')  #绘制标签为0的样本点
plt.scatter(x[y == 1, 0], x[y == 1, 1], s=30, c='r', marker='o')  #绘制标签为1的样本点
#设置坐标轴的名称并显示图形
plt.rcParams['font.sans-serif'] = 'SimHei'
plt.xlabel('科目1成绩')
plt.ylabel('科目2成绩')
plt.show()